package com.vitabuybuy.tv.ui.mine.order


import android.app.Activity
import android.content.Intent
import android.graphics.Bitmap
import android.media.MediaMetadataRetriever
import android.net.Uri
import android.os.AsyncTask
import android.os.Bundle
import android.os.Handler
import android.view.View
import androidx.core.os.bundleOf
import androidx.recyclerview.widget.LinearLayoutManager
import cc.shinichi.library.ImagePreview
import com.iceteck.silicompressorr.SiliCompressor
import com.library.common.base.BaseActivity
import com.library.common.base.LoadingDialogEntity
import com.library.common.base.MessageModel
import com.library.common.ext.dismissLoadingExt
import com.library.common.ext.logE
import com.library.common.ext.showDialogMessage
import com.library.common.ext.showLoadingExt
import com.library.common.toast.XToast
import com.library.common.util.JsonUtil
import com.library.common.util.PictureUtils
import com.library.common.util.SdCardUtil
import com.luck.picture.lib.PictureSelector
import com.vitabuybuy.tv.R
import com.vitabuybuy.tv.databinding.ActivityOrderCommentBinding
import com.vitabuybuy.tv.dto.OrderDetailDto
import com.vitabuybuy.tv.ui.mine.order.adapter.OrderCommentListAdapter
import com.vitabuybuy.tv.ui.mine.order.viewmodel.OrderViewModel
import com.vitabuybuy.tv.ui.tencent.superplay.SuperPlayVidelMainActivity
import com.vitabuybuy.tv.utils.BitmapUtils
import com.vitabuybuy.tv.utils.EventCode
import com.vitabuybuy.tv.utils.FileHelper
import com.vitabuybuy.tv.utils.StringUtil
import com.yanzhenjie.permission.AndPermission
import com.yanzhenjie.permission.runtime.Permission
import kotlinx.android.synthetic.main.activity_order_comment.*
import org.greenrobot.eventbus.EventBus
import java.io.File
import java.net.URISyntaxException
import java.util.*
import kotlin.collections.ArrayList
import kotlin.collections.HashMap


class OrderCommentActivity : BaseActivity<OrderViewModel, ActivityOrderCommentBinding>() {
    override val isUseBaseTitleBar: Boolean
        get() = true
    override val layoutId: Int
        get() = R.layout.activity_order_comment

    private lateinit var mAdapter: OrderCommentListAdapter
    private var stroeName: String? = null
    private var itemList: MutableList<OrderDetailDto.ItemListBean>? = null

    //    private val openOption by lazy { OptionsDialog(mContext) }
    private var REQUEST_CODE_CAMMER = 0x11
    private var REQUEST_CODE_VIDEO = 0x12
    private var REQUEST_FILE_POSITION = -1

    override fun onGetBundle(bundle: Bundle?) {
        itemList = bundle?.getSerializable("itemList") as? MutableList<OrderDetailDto.ItemListBean>
        stroeName = bundle?.getString("stroeName")
    }

    override fun initView(savedInstanceState: Bundle?) {
        setTitle(getString(R.string.publish_comment))
//        openOption.setBtnStr(getString(R.string.upload_video), getString(R.string.upload_image))
        mTvRight.apply {
            text = getString(R.string.publish)
            visibility = View.VISIBLE
        }
        mAdapter = OrderCommentListAdapter(stroeName)
        listview.apply {
            adapter = mAdapter
            layoutManager = LinearLayoutManager(mContext)
        }
        itemList?.run {
            mAdapter.setNewData(this)
        }
    }

    override fun eventHandling() {
        mAdapter.onItemVideoClick = { position ->
            REQUEST_FILE_POSITION = position
            AndPermission.with(this)
                .runtime()
                .permission(
                    Permission.Group.CAMERA,
                    Permission.Group.STORAGE
                )
                .onDenied {
                    if (AndPermission.hasAlwaysDeniedPermission(this, it)) {
                        // 这些权限被用户总是拒绝。
                        XToast.normal(getString(R.string.request_necessary_permissions))
                    }
                }
                .onGranted {
                    PictureUtils.openAluamOneByVideo(mContext, 15, REQUEST_CODE_VIDEO)
                }.start()
        }
        mAdapter.onItemPicClick = { position ->
            REQUEST_FILE_POSITION = position
            AndPermission.with(this)
                .runtime()
                .permission(
                    Permission.Group.CAMERA,
                    Permission.Group.STORAGE
                )
                .onDenied {
                    if (AndPermission.hasAlwaysDeniedPermission(this, it)) {
                        // 这些权限被用户总是拒绝。
                        XToast.normal(getString(R.string.request_necessary_permissions))
                    }
                }
                .onGranted {
                    var number = 0
                    for (bean in mAdapter.mData[REQUEST_FILE_POSITION].fileBean) {
                        if (bean.tag == "image") {
                            number++
                        }
                    }
                    PictureUtils.openAluamMore(
                        mContext,
                        REQUEST_CODE_CAMMER,
                        3 - number
                    )
                }.start()
        }
        mAdapter.onItemClick = { parentPos, childPos ->
            if (mAdapter.mData[parentPos].fileBean[childPos].tag == "video") {
                SuperPlayVidelMainActivity.openActivity(
                    mContext, mAdapter.mData[parentPos].fileBean[childPos].fileUrl,
                    mAdapter.mData[parentPos].fileBean[childPos].cover
                )
            } else {
                val images = ArrayList<String>()
                for (bean in mAdapter.mData[parentPos].fileBean) {
                    if (bean.tag == "image") {
                        images.add(bean.fileUrl)
                    }
                }
                ImagePreview.getInstance().setContext(mContext)
                    .setIndex(0)
                    .setShowDownButton(false)
                    .setImageList(images)
                    .setLoadStrategy(ImagePreview.LoadStrategy.NetworkAuto)
                    .setZoomTransitionDuration(300)
                    .setEnableDragClose(true)
                    .setErrorPlaceHolder(R.drawable.default_image).start()
            }
        }
        mTvRight.setOnClickListener {
            val evaluationList = ArrayList<HashMap<String, Any>>()
            for (itemBean in mAdapter.mData) {
                val params = HashMap<String, Any>()
                if (itemBean.scores == 0) {
                    XToast.normal(getString(R.string.pls_set_score))
                    return@setOnClickListener
                }
                if (itemBean.content.isNullOrEmpty()) {
                    XToast.normal(getString(R.string.pls_enter_your_comment))
                    return@setOnClickListener
                }
                params["scores"] = itemBean.scores
                params["content"] = itemBean.content
                if (!itemBean.fileBean.isNullOrEmpty()) {
                    var images = ""
                    for (image in itemBean.fileBean) {
                        if (image.tag == "image") {
                            images = "$images${image.fileUrl},"
                        }
                        if (image.tag == "video") {
                            params["videos"] = image.fileUrl
                            params["cover"] = image.cover
                        }
                    }
                    params["images"] = StringUtil.replaceEndChar(images)
                }
                params["item"] = mapOf(Pair("id", itemBean.id))
                evaluationList.add(params)
            }
            JsonUtil.toJson(evaluationList).logE()
            val params = HashMap<String, Any>()
            params["evaluationList"] = evaluationList
            viewModel.saveEvaluationList(params)
        }
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (resultCode != Activity.RESULT_OK) return
        if (requestCode == REQUEST_CODE_CAMMER) {
            val images = ArrayList<String>()
            for (image in PictureSelector.obtainMultipleResult(data)) {
                images.add(image.compressPath)
            }
            viewModel.uploadImage(images)
        } else if (requestCode == REQUEST_CODE_VIDEO) {
            val selectedVideo = PictureSelector.obtainMultipleResult(data)[0].path
            val uri = if (selectedVideo.contains("content"))
                Uri.parse(selectedVideo)
            else
                Uri.fromFile(File(selectedVideo))

            val videoPath = FileHelper.getPath(mContext, uri)
            val thumpName = "video_" + Date().time
            val thumpFile = BitmapUtils.saveBitmap(mContext, thumpName, getVideoThumb(videoPath))
//            VideoCompressAsyncTask(mContext).execute(
//                videoPath,
//                SdCardUtil.get(mContext).DEFAULT_VIDEO_PATH
//            )
            viewModel.uploadVideo(videoPath, thumpFile)

        }
    }

    private fun getVideoThumb(path: String?): Bitmap? {
        val media = MediaMetadataRetriever()
        media.setDataSource(path)
        return media.frameAtTime
    }

//    class VideoCompressAsyncTask(activity: BaseActivity<*, *>) :
//        AsyncTask<String?, String?, String?>() {
//        private val mContext = activity
//        override fun doInBackground(vararg params: String?): String? {
//            mContext.showLoadingExt("压缩中。。。")
//            val retriever = MediaMetadataRetriever()
//            retriever.setDataSource(params[0])
//            val width =
//                retriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_VIDEO_WIDTH) //宽
//            val height =
//                retriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_VIDEO_HEIGHT) //高
//            var filePath: String? = null
//            try {
//                filePath = SiliCompressor.with(mContext)
//                    .compressVideo(params[0], params[1], width.toInt(), height.toInt(), 0)
//            } catch (e: URISyntaxException) {
//                e.printStackTrace()
//            }
//            return filePath
//        }
//
//        override fun onPostExecute(result: String?) {
//            mContext.dismissLoadingExt()
//            Handler().postDelayed({
//                result?.run {
//                    val thumpName = "video_" + Date().time
//                    val thumpFile = BitmapUtils.saveBitmap(mContext, thumpName, getVideoThumb(this))
//                    ((mContext).viewModel as OrderViewModel).uploadVideo(this, thumpFile)
//                }
//            },500)
//        }
//
//        private fun getVideoThumb(path: String?): Bitmap? {
//            val media = MediaMetadataRetriever()
//            media.setDataSource(path)
//            return media.frameAtTime
//        }
//    }


    override fun handleEvent(msg: MessageModel) {
        when (msg.code) {
            6 -> {
                val filebean = ArrayList<OrderDetailDto.ItemListBean.VideoAndPicBean>()
                for (str in msg.obj as ArrayList<String>) {
                    val bean = OrderDetailDto.ItemListBean.VideoAndPicBean()
                    bean.fileUrl = str
                    bean.tag = "image"
                    filebean.add(bean)
                }
                PictureUtils.clearCache(mContext)
                mAdapter.mData[REQUEST_FILE_POSITION].fileBean.addAll(0, filebean)
                mAdapter.notifyItemChanged(REQUEST_FILE_POSITION)
            }
            7 -> {
                EventBus.getDefault().post(EventCode.update_order_detail)
                EventBus.getDefault().post(EventCode.update_order_list)
                XToast.success(getString(R.string.thank_for_your_comment))
                finish()
            }
            8 -> {
                val imageUrl = msg.msg
                val videoUrl = msg.obj as String
                val bean = OrderDetailDto.ItemListBean.VideoAndPicBean()
                bean.fileUrl = videoUrl
                bean.tag = "video"
                bean.cover = imageUrl
                mAdapter.mData[REQUEST_FILE_POSITION].fileBean.add(bean)
                mAdapter.notifyItemChanged(REQUEST_FILE_POSITION)
                PictureUtils.clearCache(mContext)
            }
        }
    }

    companion object {
        fun openActivity(
            mContext: BaseActivity<*, *>,
            itemList: MutableList<OrderDetailDto.ItemListBean>,
            stroeName: String
        ) {
            mContext.startActivity(
                bundleOf(Pair("itemList", itemList), Pair("stroeName", stroeName)),
                OrderCommentActivity::class.java
            )
        }
    }
}
